package com.woniu.airent.realm;

import com.woniu.airent.dto.HouseDto;
import com.woniu.airent.dto.UserDto;
import com.woniu.airent.service.HouseService;
import com.woniu.airent.service.UserDtoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    UserDtoService userDtoService;

    @Autowired
    HouseService houseService;

    //角色认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> roles = new HashSet<>();
        Subject subject = SecurityUtils.getSubject();
        String userName = (String) subject.getPrincipal();
        if ("admin".equals(userName)){
            roles.add("admin");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        return info;
    }

    /**
     * 登录验证
     * 通过token中的用户名密码信息，与info中接收到的从数据库中查到的用户名密码信息作比较，来进行判断用户名密码是否正确
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        Subject subject = SecurityUtils.getSubject();
        //获取session作用域
        Session session = subject.getSession();
        //接收用户对象
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //取得用户对象的用户名
        String username = token.getUsername();
        //读取用户信息
        UserDto user = userDtoService.findUserByUserName(username);

        //设置盐值
        ByteSource salt = ByteSource.Util.bytes(username);
        if (user == null){
            return null;    //此时会抛出异常
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUserName(),user.getUserPwd(),salt,this.getName());
        session.setAttribute("user",user);
        return info;

    }
}
